package org.grow.took.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.grow.took.dao.PlayerDao;
import org.grow.took.entity.DealBill;
import org.grow.took.entity.Player;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: xwg
 * @CreateDate: 2021/9/13
 */

@Service
public class PlayerService {
    @Autowired
    private PlayerDao playerDao;
//    transaction
//    一个按钮 同时修改两条数据发生的问题
//   两个人同时修改同一条数据产生的问题
    @Transactional
    public Boolean txDeal(DealBill dealBill){
//回滚到最初
        Player consumer = playerDao.findByCode(dealBill.getConsumerCode());
        if (consumer == null) {
            throw new RuntimeException("消费者不存在");
        }
//        int m = playerDao.updateGoldCoinByCode(dealBill.getConsumerCode(),
//                consumer.getGoldCoin() + dealBill.getQuantity(),consumer.getVersion());
        consumer.setGoldCoin(dealBill.getQuantity()+consumer.getGoldCoin());
        UpdateWrapper<Player> wrapper = new UpdateWrapper<>();
        wrapper.eq("playerCode",consumer.getPlayerCode());
        int m = playerDao.update(consumer, wrapper);
//        System.out.println("目前消费者已经变化了: "+playerDao.findByCode(dealBill.getConsumerCode()));
        Player supplier = playerDao.findByCode(dealBill.getSupplierCode());
        if (supplier == null) {
            throw new RuntimeException("提供者不存在");
        }
//        if (1==1){
//            throw new RuntimeException("模拟不可预测的原因");
//        }
//        try {
//            Thread.sleep(25000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        int n = playerDao.updateGoldCoinByCode(dealBill.getSupplierCode(),
//                supplier.getGoldCoin() - dealBill.getQuantity(),supplier.getVersion());
        supplier.setGoldCoin(supplier.getGoldCoin()-dealBill.getQuantity());
        UpdateWrapper<Player> wrapper2 = new UpdateWrapper<>();
        wrapper2.eq("playerCode",supplier.getPlayerCode());
        int n = playerDao.update(supplier, wrapper2);
//        LambdaUpdateWrapper<Player> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
//        lambdaUpdateWrapper.ge(Player::getPlayerCode,supplier.getPlayerCode());
//        int n = playerDao.update(supplier, lambdaUpdateWrapper);
        return (m > 0 && n > 0);
    }
}
